﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using MaxVirtual.Data;

public partial class Admin_Modules_Backend_browser : System.Web.UI.Page
{
    private GDataSource db;
    protected System.Web.UI.WebControls.Table FoldersAndFiles;
    public string FolderDescription;
    protected System.Web.UI.WebControls.Table Table1;
    protected System.Web.UI.WebControls.Table Table2;
    public string deletePath;
    public string folderPath;


    public string fileOUTPUT;

    public string sql;
    public string NDCMS_TITLE = "File Manager";

    private void Page_Load(object sender, System.EventArgs e)
    {
        deletePath = Request.Params["Delete"];
        if (deletePath != null)
        {
            File.Delete(Server.MapPath(deletePath));
            int lastSlashIndex = deletePath.LastIndexOf("/");
            folderPath = deletePath.Substring(0, lastSlashIndex);

            Response.Redirect("browser.aspx?Folder=" + folderPath);
        }
        else
            folderPath = Request.Params["Folder"];

        if (folderPath == null)
            folderPath = Request.ApplicationPath.ToString();
        else if (folderPath.EndsWith("/"))
            folderPath = folderPath.Substring(0, folderPath.Length - 1);
        FolderDescription = "虚拟目录: " + folderPath + "<br>物理目录: " + Server.MapPath(folderPath);
    }

    #region Web Form Designer generated code
    override protected void OnInit(EventArgs e)
    {
        //
        // CODEGEN: This call is required by the ASP.NET Web Form Designer.
        //
        InitializeComponent();
        base.OnInit(e);
    }

    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
        this.Load += new System.EventHandler(this.Page_Load);

    }
    #endregion

    //private void Page_Init(object sender, EventArgs e)
    //{
    //	InitializeComponent();
    //}

    public void FillFoldersAndFilesTable()
    {
        string location;
        DirectoryInfo parentDir;
        DirectoryInfo[] childDirs;
        FileInfo[] childFiles;
        int even_odd = 1;
        string even_odd_color = "style=\"background:'WHITE'\"";
        try
        {
            parentDir = new DirectoryInfo(Server.MapPath(folderPath));
            // get all the child directories and files
            childDirs = parentDir.GetDirectories();
            childFiles = parentDir.GetFiles();
        }
        catch (Exception exc)
        {
            StatusMessage.Text = exc.Message;
            return;
        }

        Response.Write("<table>");
        //是否将访问上级目录权限控制在虚拟目录的下级目录。就是说控制能不能访问虚拟目录以上的目录。
        //if (folderPath != Request.ApplicationPath.ToString())
        //{
            int lastSlashIndex = folderPath.LastIndexOf("/");
            location = folderPath.Substring(0, lastSlashIndex);
            if (location.Length == 0) location = Request.ApplicationPath.ToString();
            Response.Write("<tr><td colspan=5><a href='browser.aspx?Folder=" + location + "'>[..]</a></td></tr>");
        //}
        // add all the child directories first

        foreach (DirectoryInfo childDir in childDirs)
        {
            if ((even_odd % 2) == 1)
                even_odd_color = "style=\"background:'#e0e0e0';\"";
            else
                even_odd_color = "style=\"background:'WHITE';\"";
            location = folderPath + "/" + childDir.Name;
            location = location.Replace("//", "/");
            Response.Write("<tr " + even_odd_color + "><td><a href='browser.aspx?Folder=" + location + "'><b><i>/" + childDir.Name + "</i></b></a></td><td align=right nowrap>" + FormatSize(GetDirectorySize(childDir.FullName)) + "&nbsp;&nbsp;</td><td colspan=3>&nbsp;</td></tr>");
            even_odd++;
        }
        // now add each child file
        foreach (FileInfo childFile in childFiles)
        {
            if ((even_odd % 2) == 1)
                even_odd_color = "style=\"background:'#e0e0e0';\"";
            else
                even_odd_color = "style=\"background:'WHITE';\"";
            location = folderPath + "/" + childFile.Name;
            location = location.Replace("//", "/");
            Response.Write("<tr " + even_odd_color + "><td>" + childFile.Name + "</td><td align=right nowrap>" + FormatSize(childFile.Length) + "&nbsp;&nbsp;</td>");
            Response.Write("<td>[ <a href=javascript:popup_resize('" + location.Replace(" ", "%20") + "','3',500,550,'yes')>查&nbsp;看</a> ]</td>");
            Response.Write("<td>[ <a href='browser.aspx?Delete=" + location + "' onclick='return confirm(\"您确认要删除 [ " + childFile.Name + " ]?\");'>删&nbsp;除</a> ]</td><td>[ <a href=javascript:Rename('F" + Server.UrlEncode(location) + "')>重命名</a> ]</td></tr>");
            even_odd++;
        }
        Response.Write("</table>");
    }
    //public void BrowseFiles()
    //{
        //	Page.Init += new System.EventHandler(Page_Init);
    //}

    protected void UploadFile(object Sender, EventArgs E)
    {
        int IntE = 0;
        int IntLoop = 0;
        string StrFileName = "";
        string StrFileType = "";
        //Iterating through the Request.Files collection
        try
        {
            for (IntLoop = 0; IntLoop < Request.Files.Count; IntLoop++)
            {
                if (Request.Files[IntLoop] != null) //Checking for valid file
                {
                    // FileName gives the entire path.Use Substring function to rip of the filename.
                    StrFileName = Request.Files[IntLoop].FileName.Substring(Request.Files[IntLoop].FileName.LastIndexOf("\\") + 1);
                    StrFileType = Request.Files[IntLoop].ContentType;
                    int IntFileSize = Request.Files[IntLoop].ContentLength;
                    //Checking for the file length
                    if (IntFileSize > 0)
                        Request.Files[IntLoop].SaveAs(Server.MapPath(folderPath) + "/" + StrFileName);
                }
            }
        }
        catch (Exception e)
        {
            IntE = 1;
            Response.Write("<script> alert('上传失败 " + StrFileName + ". 请检查文件夹权限.');</script>");
        }
        if (IntE <= 0)
            Response.Redirect("browser.aspx?Folder=" + folderPath);
    }
    protected void CreateDir_Click(object sender, EventArgs e)
    {
        // build the complete path (current path + new dir name)
        string path = folderPath;
        if (path.EndsWith("/"))
            path += funcParam.Value;
        else
            path += "/" + funcParam.Value;
        try
        {
            // create the directory
            Directory.CreateDirectory(Server.MapPath(path));

            // refresh the page
            Response.Redirect("browser.aspx?Folder=" + folderPath);
        }
        catch (Exception exc)
        {
            StatusMessage.Text = exc.Message;
            StatusMessage.Visible = true;
        }
    }
    protected void DeleteDir_Click(object sender, EventArgs e)
    {
        try
        {
            // create the directory
            Directory.Delete(Server.MapPath(folderPath));

            // refresh the page
            string dirpath;
            int lastSlashIndex = folderPath.LastIndexOf("/");
            dirpath = folderPath.Substring(0, lastSlashIndex);
            if (dirpath.Length == 0) dirpath = Request.ApplicationPath.ToString();

            Response.Redirect("browser.aspx?Folder=" + dirpath);
        }
        catch (Exception exc)
        {
            StatusMessage.Text = exc.Message;
            StatusMessage.Visible = true;
        }
    }
    protected void Rename_Click(object sender, EventArgs e)
    {
        // the first char of the first param is F if the path identifies a file,
        // D otherwise. Extract the first char to determine this
        bool isFile = funcParam.Value.StartsWith("F");
        // extract the source path
        string sourcePath = Server.MapPath(funcParam.Value.Substring(1).Replace("+", " "));
        string destPath;
        string dirPath;

        try
        {
            if (isFile)
            {
                FileInfo sourceFile = new FileInfo(sourcePath);
                // create the destination path: source path dir + new name
                destPath = Path.Combine(sourceFile.Directory.FullName, funcExtraParam.Value);
                // move the file = rename
                sourceFile.MoveTo(destPath);
                dirPath = folderPath;
                
            }
            else
            {
                DirectoryInfo sourceDir = new DirectoryInfo(sourcePath);
                // create the destination path: source path dir + new name
                destPath = Path.Combine(sourceDir.Parent.FullName, funcExtraParam.Value);
                // move the directory = rename
                sourceDir.MoveTo(destPath);

                int lastSlashIndex = folderPath.LastIndexOf("/");
                dirPath = folderPath.Substring(0, lastSlashIndex);
                if (dirPath.Length == 0) dirPath = Request.ApplicationPath.ToString();
                dirPath = dirPath + "/" + funcExtraParam.Value;
            }
            Response.Redirect("browser.aspx?Folder=" + dirPath);
        }
        catch (Exception exc)
        {
            StatusMessage.Text = exc.Message;
            StatusMessage.Visible = true;
        }
    }
    protected long GetDirectorySize(string path)
    {
        long dirSize = 0;
        DirectoryInfo dir = new DirectoryInfo(path);

        // add file sizes
        foreach (FileInfo file in dir.GetFiles())
            dirSize += file.Length;

        // add the size of subdirectories
        foreach (DirectoryInfo subdir in dir.GetDirectories())
            dirSize += GetDirectorySize(subdir.FullName);

        return dirSize;
    }

    protected string FormatSize(double fileSize)
    {
        if (fileSize < 1024)
            return String.Format("{0:N0} &nbsp;B", fileSize);
        else if (fileSize < 1024 * 1024)
            return String.Format("{0:N2} KB", fileSize / 1024);
        else
            return String.Format("{0:N2} MB", fileSize / (1024 * 1024));
    }
}
